package com.xatz.scanner

import android.app.Activity
import android.app.AlertDialog
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.text.Editable
import android.view.View
import android.view.WindowManager
import android.view.inputmethod.InputMethodManager
import android.widget.AdapterView
import android.widget.ArrayAdapter
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.view.isGone
import com.xatz.scanner.bean.CarInfoBean
import com.xatz.scanner.bean.OrderInfoBean
import com.xatz.scanner.bean.ResultDataBean
import com.xatz.scanner.databinding.ActivityArrivalConfirmationDetailsBinding
import com.xatz.scanner.databinding.DialogInvalidGrowthBinding
import com.xatz.scanner.databinding.ViewArrivalConfirmationBinding
import org.xmlpull.v1.XmlPullParser
import org.xmlpull.v1.XmlPullParserFactory
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import timber.log.Timber
import java.io.StringReader


/**
 * Created by tdq on 2022/1/4.
 */
class ArrivalConfirmationDetailsActivity : AppCompatActivity(), View.OnClickListener {

    private var mBinding: ActivityArrivalConfirmationDetailsBinding? = null

    private val mLists = mutableListOf<OrderInfoBean>()
    private val mWuXiaoLists = mutableListOf<String>()

    private val mCarInfoBean by lazy { intent.getParcelableExtra("CarInfoBean") as CarInfoBean? }

    private var soCode = ""

    private val userAccount by lazy {
        getSharedPreferences(
            Constant.configName,
            Context.MODE_PRIVATE
        ).getString(Constant.userAccount, "").toString()
    }

    private val userBz: String by lazy {
        getSharedPreferences(
            Constant.configName,
            Context.MODE_PRIVATE
        ).getString(Constant.userBz, "").toString()
    }

    private val mService by lazy {
        ScannerRetrofitClient().getService(
            ScannerService::class.java,
            ScannerService.baseUrl
        )
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBinding = ActivityArrivalConfirmationDetailsBinding.inflate(layoutInflater)
        setContentView(mBinding?.root)
        getWuXiaoReasons()
        soCode = mCarInfoBean?.C_DELIVERY.toString()
        initData()
        mBinding?.btnInvalidGrowth?.setOnClickListener(this)
        mBinding?.btnLook?.setOnClickListener(this)
        mBinding?.toolbarLayout?.setRightViewOnClick(this)

        if (userBz == "KFB") {
//            mBinding?.btnInvalidGrowth?.visibility = View.VISIBLE
            mBinding?.toolbarLayout?.rightText = "无效出厂"
        }
    }

    private fun initView() {
        if (mLists.size > 0) {
            mBinding?.tvSoCode?.text = mLists[0].C_DELIVERY
            mBinding?.tvCarNumber?.text = mLists[0].C_CUST_NAME
            mBinding?.tvDriverInfo?.text = mLists[0].C_SHIP_NO
            mBinding?.tvTime?.text = mLists[0].C_TIHUOREN
            mBinding?.tvOrderStatus?.text = mLists[0].C_THKF
            mBinding?.tvRemark?.text = mLists[0].C_YY

            mBinding?.tvCarNum?.text = mLists[0].C_PLATE_NUMBER
            mBinding?.tvLoadLimit?.text = mLists[0].C_XZ
            mBinding?.tvTareTime?.text = mLists[0].C_PZSJ
            mBinding?.tvTare?.text = mLists[0].C_PZ
            mBinding?.tvActualProductName?.text = mLists[0].C_MAT_CODE
            mBinding?.tvActualSpec?.text = mLists[0].C_STR_GRD
            mBinding?.tvActualFurnace?.text = mLists[0].C_STR_GRD
        }

//        if(mLists[0].C_LOAD_SURE != "1"){
//            showInputMethod()
//        }
    }

    private fun showInputMethod() {
        val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS)
    }

    private fun initData() {
        mService.getDZTiDanInfo(soCode).enqueue(object : Callback<String> {
            @RequiresApi(Build.VERSION_CODES.M)
            override fun onResponse(call: Call<String>, response: Response<String>) {
                if (response.isSuccessful) {
                    response.body()?.let { parseOrderInfoXMLWithPull(it) }
                    for (i in 0 until mLists.size) {
                        val itemBinding = ViewArrivalConfirmationBinding.inflate(layoutInflater)
                        mBinding?.llContainer?.addView(itemBinding.root)
                        itemBinding.tvSoCode.text = mLists[i].C_THKF
                        itemBinding.tvCarNumber.text = mLists[i].C_MAT_CODE
                        itemBinding.tvDriverInfo.text = mLists[i].GUIGE
                        itemBinding.tvTime.text = mLists[i].N_PLAN_CNT
                        itemBinding.tvWeight2.text = mLists[i].N_PLAN_WGT
                        itemBinding.tvOrderPerson.text = userAccount
                        if (mLists[i].C_LOAD_SURE == "1") {
                            itemBinding.tvOrderStatus.text =
                                Editable.Factory.getInstance().newEditable(mLists[i].N_LOAD_CNT)
                        }else{
                            itemBinding.tvOrderStatus.text =
                                Editable.Factory.getInstance().newEditable(mLists[i].N_PLAN_CNT)
                        }

                        itemBinding.btnConfirm.setOnClickListener {
                            val number = itemBinding.tvOrderStatus.text.toString()
                            if (itemBinding.btnConfirm.text == "取消确认") {
                                itemBinding.tvOrderStatus.isEnabled = true
                                itemBinding.btnConfirm.text = "确认件数"
                                itemBinding.tvOrderStatus.isFocusable = true
                                itemBinding.tvOrderStatus.isFocusableInTouchMode = true
                                itemBinding.tvOrderStatus.requestFocus()
                                showInputMethod()
                                return@setOnClickListener
                            } else {
                                if (number.isBlank()) {
                                    toast("请确认件数！")
                                    return@setOnClickListener
                                }

                                when {
                                    number == "0" -> {
                                        val dialog =
                                            AlertDialog.Builder(this@ArrivalConfirmationDetailsActivity)
                                                .setTitle("确认件数")
                                                .setMessage("装车数量为0!是否继续确认?")
                                                .setPositiveButton("确定") { dialog, _ ->
                                                    dialog.dismiss()
                                                    beSureLoadAmountOnNet(
                                                        itemBinding,
                                                        number,
                                                        mLists[i].C_DELIVERY_ID
                                                    )
                                                }
                                                .setNegativeButton("取消") { dialog, _ ->
                                                    dialog.dismiss()
                                                }
                                        dialog.show()
                                    }
                                    number.toDouble() > mLists[i].N_PLAN_CNT.toDouble() -> {
                                        val dialog =
                                            AlertDialog.Builder(this@ArrivalConfirmationDetailsActivity)
                                                .setTitle("确认件数")
                                                .setMessage("装车数量超过计划数量!是否继续确认?")
                                                .setPositiveButton("确定") { dialog, _ ->
                                                    dialog.dismiss()
                                                    beSureLoadAmountOnNet(
                                                        itemBinding,
                                                        number,
                                                        mLists[i].C_DELIVERY_ID
                                                    )
                                                }
                                                .setNegativeButton("取消") { dialog, _ ->
                                                    dialog.dismiss()
                                                }
                                        dialog.show()
                                    }
                                    else -> {
                                        beSureLoadAmountOnNet(
                                            itemBinding,
                                            number,
                                            mLists[i].C_DELIVERY_ID
                                        )
                                    }
                                }

                            }

                        }
                        if (mLists[i].C_LOAD_SURE == "1") {
                            itemBinding.btnConfirm.setBackgroundColor(
                                resources.getColor(
                                    R.color.teal_700,
                                    theme
                                )
                            )
                            itemBinding.btnConfirm.text = "取消确认"
                            itemBinding.tvOrderStatus.isEnabled = false
                        } else {
                            itemBinding.btnConfirm.setBackgroundColor(
                                resources.getColor(
                                    R.color.color_387cf9,
                                    theme
                                )
                            )
                            itemBinding.btnConfirm.text = "确认件数"
                            itemBinding.tvOrderStatus.isEnabled = true
                        }

                        if (mLists[i].C_WUXIAO.isNotBlank() && mLists[i].C_WUXIAO_PERSON.isNotBlank()) {
//                            mBinding?.btnInvalidGrowth?.visibility = View.GONE
                            mBinding?.toolbarLayout?.rightTextColor = ContextCompat.getColor(
                                this@ArrivalConfirmationDetailsActivity,
                                R.color.color_999
                            )
                            itemBinding.btnConfirm.visibility = View.GONE
                            itemBinding.tvOrderStatus.isEnabled = false
                        }
                    }
                    initView()
                }
            }

            override fun onFailure(call: Call<String>, t: Throwable) {
                Timber.e(t)
            }

        })
    }

    private fun beSureLoadAmountOnNet(
        itemBinding: ViewArrivalConfirmationBinding,
        number: String,
        C_DELIVERY_ID: String
    ) {
        mService.beSureLoadAmount(
            userAccount,
            soCode,
            C_DELIVERY_ID,
            number
        )
            .enqueue(object : Callback<String> {
                @RequiresApi(Build.VERSION_CODES.M)
                override fun onResponse(
                    call: Call<String>,
                    response: Response<String>
                ) {
                    if (response.isSuccessful) {
                        val result = response.body()
                            ?.let { parseResultXMLWithPull(it) }
                        if (result != null && result.resultCode == "0") {
                            itemBinding.btnConfirm.setBackgroundColor(
                                resources.getColor(
                                    R.color.teal_700,
                                    theme
                                )
                            )
                            itemBinding.btnConfirm.text = "取消确认"
                            itemBinding.tvOrderStatus.isEnabled =
                                false
                        } else {
                            result?.let {
                                toast(it.resultMsg)
                            }
                        }
                    }
                }

                override fun onFailure(
                    call: Call<String>,
                    t: Throwable
                ) {
                    Timber.e(t)
                    toast("确认失败！")
                }
            })
    }

    private fun parseOrderInfoXMLWithPull(xmlData: String) {
        mLists.clear()
        var orderInfoBean: OrderInfoBean? = null
        try {
            val factory = XmlPullParserFactory.newInstance()
            val xmlPullParser = factory.newPullParser()
            xmlPullParser.setInput(StringReader(xmlData))
            var eventType = xmlPullParser.eventType
            while (eventType != XmlPullParser.END_DOCUMENT) {
                val nodeName = xmlPullParser.name
                when (eventType) {
                    XmlPullParser.START_DOCUMENT -> {
                    }
                    XmlPullParser.START_TAG -> {
                        when (nodeName) {
                            "Table" -> {
                                orderInfoBean = OrderInfoBean(
                                    "",
                                    "",
                                    "",
                                    "",
                                    "",
                                    "",
                                    "",
                                    "",
                                    "",
                                    "",
                                    "",
                                    "",
                                    "",
                                    "",
                                    "",
                                    "",
                                    "",
                                    "",
                                    "",
                                    "",
                                    "",
                                )
                            }
                            "C_DELIVERY" -> orderInfoBean?.C_DELIVERY = xmlPullParser.nextText()
                            "C_CUST_NAME" -> orderInfoBean?.C_CUST_NAME = xmlPullParser.nextText()
                            "C_SHIP_NO" -> orderInfoBean?.C_SHIP_NO = xmlPullParser.nextText()
                            "C_WUXIAO" -> orderInfoBean?.C_WUXIAO = xmlPullParser.nextText()
                            "C_WUXIAO_PERSON" -> orderInfoBean?.C_WUXIAO_PERSON =
                                xmlPullParser.nextText()
                            "C_TIHUOREN" -> orderInfoBean?.C_TIHUOREN = xmlPullParser.nextText()
                            "C_LOAD_PERSON" -> orderInfoBean?.C_LOAD_PERSON =
                                xmlPullParser.nextText()
                            "C_LOAD_SURE" -> orderInfoBean?.C_LOAD_SURE = xmlPullParser.nextText()
                            "N_LOAD_CNT" -> orderInfoBean?.N_LOAD_CNT = xmlPullParser.nextText()
                            "C_PLATE_NUMBER" -> orderInfoBean?.C_PLATE_NUMBER =
                                xmlPullParser.nextText()
                            "C_XZ" -> orderInfoBean?.C_XZ = xmlPullParser.nextText()
                            "C_STR_GRD" -> orderInfoBean?.C_STR_GRD = xmlPullParser.nextText()
                            "C_PZ" -> orderInfoBean?.C_PZ = xmlPullParser.nextText()
                            "C_YY" -> orderInfoBean?.C_YY = xmlPullParser.nextText()
                            "C_PZSJ" -> orderInfoBean?.C_PZSJ = xmlPullParser.nextText()
                            "C_DELIVERY_ID" -> orderInfoBean?.C_DELIVERY_ID =
                                xmlPullParser.nextText()
                            "C_THKF" -> orderInfoBean?.C_THKF = xmlPullParser.nextText()
                            "C_MAT_CODE" -> orderInfoBean?.C_MAT_CODE = xmlPullParser.nextText()
                            "GUIGE" -> orderInfoBean?.GUIGE = xmlPullParser.nextText()
                            "N_PLAN_CNT" -> orderInfoBean?.N_PLAN_CNT = xmlPullParser.nextText()
                            "N_PLAN_WGT" -> orderInfoBean?.N_PLAN_WGT = xmlPullParser.nextText()
                        }
                    }
                    XmlPullParser.END_TAG -> {
                        if ("Table" == xmlPullParser.name) {
                            orderInfoBean?.let { mLists.add(it) }
                            orderInfoBean = null
                        }
                    }
                }
                eventType = xmlPullParser.next()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }

    }

    private fun parseResultXMLWithPull(xmlData: String): ResultDataBean? {
        var resultDataBean: ResultDataBean? = null
        try {
            val factory = XmlPullParserFactory.newInstance()
            val xmlPullParser = factory.newPullParser()
            xmlPullParser.setInput(StringReader(xmlData))
            var eventType = xmlPullParser.eventType
            while (eventType != XmlPullParser.END_DOCUMENT) {
                val nodeName = xmlPullParser.name
                when (eventType) {
                    XmlPullParser.START_DOCUMENT -> {
                    }
                    XmlPullParser.START_TAG -> {
                        when (nodeName) {
                            "ResultEntity" -> {
                                resultDataBean = ResultDataBean("", "")
                            }
                            "resultCode" -> resultDataBean?.resultCode = xmlPullParser.nextText()
                            "resultMsg" -> resultDataBean?.resultMsg = xmlPullParser.nextText()
                        }
                    }
                    XmlPullParser.END_TAG -> {
                        if ("ResultEntity" == xmlPullParser.name) {

                        }
                    }
                }
                eventType = xmlPullParser.next()
            }
            return resultDataBean
        } catch (e: Exception) {
            e.printStackTrace()
            return null
        }
    }

    /**
     * 隐藏软键盘(只适用于Activity，不适用于Fragment)
     */
    fun hideSoftKeyboard(activity: Activity) {
        val view = activity.currentFocus
        if (view != null) {
            val inputMethodManager =
                activity.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
            inputMethodManager.hideSoftInputFromWindow(
                view.windowToken,
                InputMethodManager.HIDE_NOT_ALWAYS
            )
        }
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.tvRightMenu -> {
                hideSoftKeyboard(this)
                val dialog = AlertDialog.Builder(this).create()
                dialog.show()
                val window = dialog.window
                window?.clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM)
                val dialogBinding = DialogInvalidGrowthBinding.inflate(layoutInflater)
                window?.setContentView(dialogBinding.root)
                dialogBinding.etRemark.run {
                    isFocusableInTouchMode = true
                    isFocusable = true
                    requestFocus()
                }
                dialogBinding.etRemark.postDelayed({
                    showInputMethod()
                }, 200)
                dialogBinding.tvCancel.setOnClickListener {
                    hideKeyboard()
                    dialog.dismiss()
                }
                dialogBinding.tvConfirm.setOnClickListener {
                    val remark = dialogBinding.etRemark.text.toString()
                    if (remark.isBlank()) {
                        toast("请输入备注")
                        return@setOnClickListener
                    }

                    dialog.dismiss()

                    mService.beWuXiaoChuChang(
                        userAccount,
                        soCode,
                        remark
                    )
                        .enqueue(object : Callback<String> {
                            override fun onResponse(
                                call: Call<String>,
                                response: Response<String>
                            ) {
                                if (response.isSuccessful) {
                                    val result = response.body()?.let { parseResultXMLWithPull(it) }

                                    if (result != null && result.resultCode == "0") {
                                        toast("操作成功！")
                                        finish()
                                    } else {
                                        result?.let {
                                            toast(it.resultMsg)
                                        }
                                    }

                                }
                            }

                            override fun onFailure(
                                call: Call<String>,
                                t: Throwable
                            ) {
                                Timber.e(t)
                                toast("操作失败！")
                            }
                        })
                }
                dialogBinding.spinInvalid.adapter = ArrayAdapter(
                    this,
                    R.layout.spinner_select_text,
                    R.id.tvCarNum,
                    mWuXiaoLists
                )
                dialogBinding.spinInvalid.onItemSelectedListener =
                    object : AdapterView.OnItemSelectedListener {
                        override fun onItemSelected(
                            parent: AdapterView<*>?,
                            view: View?,
                            position: Int,
                            id: Long
                        ) {
                            dialogBinding.etRemark.text =
                                Editable.Factory.getInstance().newEditable(mWuXiaoLists[position])
                            dialogBinding.etRemark.setSelection(dialogBinding.etRemark.text.length)
                        }

                        override fun onNothingSelected(parent: AdapterView<*>?) {
                        }

                    }

                if (mLists[0].C_WUXIAO.isNotBlank() && mLists[0].C_WUXIAO_PERSON.isNotBlank()) {
                    dialogBinding.spinInvalid.isEnabled = false
                    dialogBinding.tvCancel.isGone = true
                    dialogBinding.tvConfirm.isGone = true
                    dialogBinding.tvLine2.isGone = true
                    dialogBinding.etRemark.text =
                        Editable.Factory.getInstance().newEditable(mLists[0].C_WUXIAO)

                }

            }
            R.id.btnLook -> {
                startActivity(
                    Intent(this, LookBarCodeActivity::class.java).putExtra(
                        "code",
                        soCode
                    )
                )
            }
            else -> Timber.e("click no view")
        }
    }

    private fun getWuXiaoReasons() {
        mService.getWuXiaoReasons()
            .enqueue(object : Callback<String> {
                override fun onResponse(
                    call: Call<String>,
                    response: Response<String>
                ) {
                    if (response.isSuccessful) {
                        response.body()?.let { parseWuXiaoReasonsXMLWithPull(it) }
                    }
                }

                override fun onFailure(
                    call: Call<String>,
                    t: Throwable
                ) {
                    Timber.e(t)
                    toast("操作失败！")
                }
            })
    }

    private fun parseWuXiaoReasonsXMLWithPull(xmlData: String) {
        mWuXiaoLists.clear()
        var wuXiaoReason: String? = null
        try {
            val factory = XmlPullParserFactory.newInstance()
            val xmlPullParser = factory.newPullParser()
            xmlPullParser.setInput(StringReader(xmlData))
            var eventType = xmlPullParser.eventType
            while (eventType != XmlPullParser.END_DOCUMENT) {
                val nodeName = xmlPullParser.name
                when (eventType) {
                    XmlPullParser.START_DOCUMENT -> {
                    }
                    XmlPullParser.START_TAG -> {
                        when (nodeName) {
                            "Table" -> {
                                wuXiaoReason = ""
                            }
                            "C_WUXIAO" -> wuXiaoReason = xmlPullParser.nextText()
                        }
                    }
                    XmlPullParser.END_TAG -> {
                        if ("Table" == xmlPullParser.name) {
                            if (wuXiaoReason?.isNotBlank() == true) {
                                mWuXiaoLists.add(wuXiaoReason)
                            }
                            wuXiaoReason = null
                        }
                    }
                }
                eventType = xmlPullParser.next()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }

    }
}